package com.zxq.ruoyi.network.tcp.handler.impl;

import com.zxq.memory.ByteArrayPools;
import com.zxq.memory.ByteCombination;
import com.zxq.ruoyi.network.tcp.handler.dispatch.TCPDispatchHandler;
import com.zxq.ruoyi.network.tcp.util.CrcUtils;
import io.netty.channel.ChannelHandler;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class IEC104DispatchHandler extends TCPDispatchHandler {

    /**
     * 第一个字节
     */
    final byte headFlag = (byte) 0xFF;

    /**
     * 第二个字节
     */
    final byte secondFlag = 0x18;





    @Override
    public boolean isThisFrame() {
       byte head = in.readByte();
       byte second = in.readByte();
       in.resetReaderIndex();
       if((head == headFlag) && (second == secondFlag)) {
           return true;
       }
       return false;
    }


    @Override
    protected Boolean isRegisterFrame() {
        return false;
    }

    @Override
    protected byte[] trimFrame() {
        while (in.readableBytes() < 7) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        byte[] headBytes = ByteArrayPools.getBytes(7 + "");
        in.writeBytes(headBytes);
        int number1 = 0;
        int number2 = 0;
        if(headBytes[5] < 0) {
            number1 =  number1 + 256;
        }
        if(headBytes[6] < 0) {
            number2 =  number2 + 256;
        }
        Integer len =  number1 + number2 * 256;
        while (in.readableBytes() < len + 2) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        byte[] dataBuff = ByteArrayPools.getBytes(len + "");
        in.writeBytes(dataBuff);

        byte[] crcBuff = ByteArrayPools.getBytes(2 + "");
        in.writeBytes(crcBuff);

        byte[] waitCrcBuff = ByteCombination.combinationContent(headBytes,dataBuff);
        byte[] localCrcBuff =  CrcUtils.crc16(waitCrcBuff);

        if(crcBuff[0] == localCrcBuff[0] && crcBuff[1] == localCrcBuff[1]) {
            byte[] frame = ByteCombination.combinationContent(waitCrcBuff,crcBuff);
            return frame;
        }
        log.info("crc is error!");
        return null;
    }
}
